package Utils;



import springmvc.common.CriteriaExample;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

public class Bean2CriteriaUtil {

	public static CriteriaExample Bean2Criteria(Object o) throws IllegalArgumentException, IllegalAccessException {

		CriteriaExample criteriaList = new CriteriaExample();

		Field[] fields = o.getClass().getDeclaredFields();

		for (Field field : fields) {
			Class<?> type = field.getType();

			Object value = field.get(o);

			String strName = field.getName();
			if (value != null && value.toString().length() > 0) {
				CriteriaExample.Criteria criteria = new CriteriaExample.Criteria();
				if (value.getClass().equals(Date.class)) {
					criteria.greaterThanOrEqual(strName, value);
				} else if (value.getClass().equals(int.class) || value.getClass().equals(float.class)
						|| value.getClass().equals(double.class)) {

				}

				else if (value.getClass().isArray()) {

				} else if (value instanceof List) {
					List list = (List) value;
					if (!list.isEmpty()) {
						Object listvalue = list.get(0);

						if (listvalue.getClass().equals(String.class)) {
							criteria.in(strName, (List<String>) value);
						} else if (listvalue.getClass().equals(int.class)
								|| listvalue.getClass().equals(Integer.class)) {
							criteria.in(strName, (List<Integer>) value);
						} else if (listvalue.getClass().equals(double.class)
								|| listvalue.getClass().equals(Double.class)) {
							criteria.in(strName, (List<Double>) value);
						} else if (listvalue.getClass().equals(float.class)
								|| listvalue.getClass().equals(Float.class)) {
							criteria.in(strName, (List<Float>) value);
						}

						else if (listvalue.getClass().equals(Date.class)) {
							criteria.in(strName, (List<Date>) value);
						}
					}

				} else if (value.getClass().equals(Integer.class) || value.getClass().equals(Float.class)
						|| value.getClass().equals(Double.class)) {
					criteria.equal(strName, value);
				}
				if (criteria.isValid()) {
					criteriaList.addCriteria(criteria);
				}
			}

		}

		return criteriaList;

	}

}
